<?php
class ControllerProductCategory extends FrontController {
	protected $filter_attribute = array();
	
	public function index() {
		global $CATEGORIES, $CATEGORY;
		
		if (!$CATEGORY) {
			return $this->forward('error/not_found');
		}
		
		M('catalog/category');
		M('catalog/product');
		
		$sort = G('sort', 'sort_order');
		$order = G('order', 'asc');
		$attribute_filter = G('af', '');
		$page = (int) G('page', 1);
		$limit = (int) G('limit', C('config_catalog_limit'));
		
		foreach (explode(',', $CATEGORY['path']) as $category_id) {
			$this->data['breadcrumbs'][] = array(
				'text'      => $CATEGORIES[$category_id]['name'],
				'href'      => $CATEGORIES[$category_id]['link'],
				'separator' => $this->_['text_separator']
			);
		}
		$category_id = $CATEGORY['id'];
			
		$category_info = $this->model_catalog_category->getCategory($category_id);
		
		$this->document->setTitle(!empty($category_info['seo_title']) ? $category_info['seo_title'] : $category_info['name']);
		$this->document->setDescription($category_info['meta_description']);
		$this->document->setKeywords($category_info['meta_keyword']);

		$this->data['heading_title'] = $category_info['name'];
		$this->data['text_compare'] = sprintf($this->_['text_compare'], (isset($this->session->data['compare']) ? count($this->session->data['compare']) : 0));
		
		$this->data['continue'] = HTTP_SERVER;
		
		if ($category_info['image']) {
			$this->data['thumb'] = thumb($category_info['image'], C('config_image_category_width'), C('config_image_category_height'));
		} else {
			$this->data['thumb'] = '';
		}

		$this->data['description'] = v5_html_entity_decode($category_info['description']);
		$this->data['compare'] = U('product/compare');
		
		$this->data['products'] = array();		
		
		if (!empty($category_info['attribute_ids'])) {
			$attributes = $this->model_catalog_category->getCategoryAttributes($category_id, $category_info['attribute_ids']);
			
			if ($attribute_filter) {
				$params = explode('|', $attribute_filter);
				foreach ($params as $param) {
					if (strpos($param, '_') !== FALSE) {
						list($attribute_id, $attribute_value) = explode('_', $param, 2);
						$attribute_id = intval($attribute_id);												
						if (isset($attributes[$attribute_id])) {						
							$this->filter_attribute[$attribute_id] = $attribute_value;
						}
					}
				}
			}
			
			$url = $this->request->query('category_id,sort,order,limit');
			
			$this->data['attributes'] = array();			
			foreach ($attributes as $attribute_id => $attribute) {
			
				$values = array();
				
				$values[] = array(
					'link' => U('product/category', $url . $this->getAttributeUrl($attribute_id)),
					'value' => $this->_['text_all'],
					'selected' => !isset($this->filter_attribute[$attribute_id])
				);
				
				foreach ($attribute['values'] as $idx => $value) {
					$values[] = array(
						'link' => U('product/category', $url . $this->getAttributeUrl($attribute_id, $value)),
						'value' => $value,
						'selected' => isset($this->filter_attribute[$attribute_id]) ? ($this->filter_attribute[$attribute_id] == $value) : false
					);
				}
				
				$this->data['attributes'][] = array(
					'name' => $attribute['name'],
					'values' => $values
				);
			}			
		}
		
		$data = array(
			'filter_category_id' => $category_id,
			'filter_attribute'   => $this->filter_attribute,
			'filter_sub_category' => true,
			'sort'               => $sort,
			'order'              => $order,
			'start'              => ($page - 1) * $limit,
			'limit'              => $limit
		);
		$product_total = $this->model_catalog_product->getTotalProducts($data);
		$results = $this->model_catalog_product->getProducts($data);

		foreach ($results as $result) {

			$this->data['products'][] = array(
				'product_id'  => $result['product_id'],
				'thumb'       => thumb($result['image'], C('config_image_product_width'), C('config_image_product_height')),
				'name'        => $result['name'],
				'summary'     => v5_html_entity_decode($result['summary']),
				'price'       => pprintf($result['price'], $result['tax_class_id']),
				'special'     => pprintf($result['special'], $result['tax_class_id']),
				'tax'         => C('config_tax') ? currency((float)$result['special'] ? $result['special'] : $result['price']) : false,
				'rating'      => C('config_review_status') ? $result['rating'] : false,
				'reviews'     => sprintf($this->_['text_reviews'], (int)$result['reviews']),
				'href'        => $result['link']
			);
		}

		$url = $this->request->query('category_id,af,limit');

		$this->data['sorts'] = array();

		$this->data['sorts'][] = array(
			'text'  => $this->_['text_default'],
			'value' => 'sort_order-asc',
			'href'  => U('product/category', $url . '&sort=sort_order&order=asc')
		);

		$this->data['sorts'][] = array(
			'text'  => $this->_['text_price_asc'],
			'value' => 'price-asc',
			'href'  => U('product/category', $url . '&sort=price&order=asc')
		);

		$this->data['sorts'][] = array(
			'text'  => $this->_['text_price_desc'],
			'value' => 'price-desc',
			'href'  => U('product/category', $url . '&sort=price&order=desc')
		);

		$this->data['sorts'][] = array(
				'text'  => $this->_['text_release_date'],
				'value' => 'date_added-desc',
				'href'  => U('product/category', $url . '&sort=date_added&order=desc')
		);
		
		if (C('config_review_status')) {
			$this->data['sorts'][] = array(
				'text'  => $this->_['text_rating_desc'],
				'value' => 'rating-desc',
				'href'  => U('product/category', $url . '&sort=rating&order=desc')
			);
			$this->data['sorts'][] = array(
				'text'  => $this->_['text_most_reviews'],
				'value' => 'reviews-desc',
				'href'  => U('product/category', $url . '&sort=reviews&order=desc')
			);
		}
		
		$url = $this->request->query('category_id,af,sort,order');

		$this->data['limits'] = array();

		$this->data['limits'][] = array(
			'text'  => C('config_catalog_limit'),
			'value' => C('config_catalog_limit'),
			'href'  => U('product/category', $url . '&limit=' . C('config_catalog_limit'))
		);

		for($i = 25; $i <= 100; $i += 25) {
			$this->data['limits'][] = array(
				'text'  => $i,
				'value' => $i,
				'href'  => U('product/category', $url . "&limit=$i")
			);
		}
				
		$url = $this->request->query('sort,af,order,limit,category_id');
		$url = U('product/category', $url . '&page={page}');
		$this->data['pagination'] = $this->pagination($product_total, $page, $url, $limit)->render();

		$this->data['sort'] = $sort;
		$this->data['order'] = $order;
		$this->data['limit'] = $limit;

		$template = empty($category_info['template']) ? 'category.tpl' : $category_info['template'];
		$this->display("product/$template");
  	}
	
	protected function getAttributeUrl($attribute_id, $attribute_value = null) {
		$url = '';
		if ($attribute_value != null) $url = "{$attribute_id}_${attribute_value}";
		foreach ($this->filter_attribute as $id => $value) {
			if ($attribute_id != $id) {
				$url .= "|{$id}_{$value}";
			}
		}
		$url = trim($url, '|');
		return $url ? "&af=" . $url : '';
	}
}
?>